import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'



const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/index'
    }, {
      path: '/login',
      component: () => import('../pages/Login.vue')
    }, {
      path: '/index',
      component: () => import('../pages/Index.vue'),
      redirect: '/index/index',
      children: [{
        path: 'goods',
        name: 'goods',
        component: () => import('../pages/subpage/Goods.vue')
      }, {
        path: 'category',
        name: 'category',
        component: () => import('../pages/subpage/Category.vue')
      }, {
        path: 'index',
        name: 'index',
        component: () => import('../pages/subpage/Index.vue')
      }, {
        path: 'person',
        name: 'person',
        component: () => import('../pages/subpage/Person.vue')
      }]
    }]
})

// 路由白名单
const whitePath = ['/login']

router.beforeEach((to, from) => {

  const userStore = useUserStore()
  // 判断是否有 token
  if (userStore.token) {
    if (to.path === '/login') {
      // 不能跳转到登录页
      return '/'
    } else {
      return true
    }
  }

  // 没有 token
  if (whitePath.includes(to.path)) {
    // 在白名单下
    return true
  } else {
    // 不在则要登录
    return `/login?redirectUrl=${to.path}`
  }
})
export default router